package com.itools.core.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @project: itools-backend
 * @description: 自定义返回结果：未登录或登录过期
 * @author: XUCHANG
 * @create: 2021-06-22 13:37
 */
@Component
@Slf4j
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Map<String, Object> map = new HashMap<>();
        map.put("returnCode",401);
        map.put("success",false);
        map.put("data",null);
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            map.put("returnMsg","暂未登录或token已经过期");
            response.getWriter().write(objectMapper.writeValueAsString(map));
        } catch (IOException e) {
            log.error("无效 token 异常类重写",e);
        }
    }
}
